package org.example.managere.controller.feibiao;

import org.example.managere.dto.feibiao.AmKnowledgeRelationDto;
import org.example.managere.entity.feibiao.AmKnowledgeRelation;
import org.example.managere.repository.feibiao.AmKnowledgeRelationRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import jakarta.persistence.criteria.Predicate;
import jakarta.validation.Valid;
import java.util.*;

/**
 * 知识图谱实体关系网络表 Controller
 */
@RestController
@RequestMapping("/api/feibiao/knowledge/relation")
public class AmKnowledgeRelationController {

    @Autowired
    private AmKnowledgeRelationRepository relationRepository;

    /**
     * 分页查询
     */
    @GetMapping
    public Page<AmKnowledgeRelation> list(@RequestParam(defaultValue = "0") int page,
                                          @RequestParam(defaultValue = "10") int size,
                                          @RequestParam(defaultValue = "relationshipId,asc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        return relationRepository.findAll(pageable);
    }

    /**
     * 条件搜索（支持entityId1/entityId2/relationshipType模糊）
     */
    @GetMapping("/search")
    public Page<AmKnowledgeRelation> search(@RequestParam(required = false) String entityId1,
                                            @RequestParam(required = false) String entityId2,
                                            @RequestParam(required = false) String relationshipType,
                                            @RequestParam(defaultValue = "0") int page,
                                            @RequestParam(defaultValue = "10") int size,
                                            @RequestParam(defaultValue = "relationshipId,asc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        Specification<AmKnowledgeRelation> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (entityId1 != null && !entityId1.isEmpty()) {
                predicates.add(cb.like(root.get("entityId1"), "%" + entityId1 + "%"));
            }
            if (entityId2 != null && !entityId2.isEmpty()) {
                predicates.add(cb.like(root.get("entityId2"), "%" + entityId2 + "%"));
            }
            if (relationshipType != null && !relationshipType.isEmpty()) {
                predicates.add(cb.like(root.get("relationshipType"), "%" + relationshipType + "%"));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return relationRepository.findAll(spec, pageable);
    }

    /**
     * 新增
     */
    @PostMapping
    public AmKnowledgeRelation create(@Valid @RequestBody AmKnowledgeRelationDto dto) {
        AmKnowledgeRelation entity = new AmKnowledgeRelation();
        BeanUtils.copyProperties(dto, entity);
        return relationRepository.save(entity);
    }

    /**
     * 更新
     */
    @PutMapping("/{relationshipId}")
    public AmKnowledgeRelation update(@PathVariable String relationshipId, @Valid @RequestBody AmKnowledgeRelationDto dto) {
        Optional<AmKnowledgeRelation> optional = relationRepository.findById(relationshipId);
        if (!optional.isPresent()) {
            throw new RuntimeException("记录不存在");
        }
        AmKnowledgeRelation entity = optional.get();
        BeanUtils.copyProperties(dto, entity, "relationshipId");
        return relationRepository.save(entity);
    }

    /**
     * 详情
     */
    @GetMapping("/{relationshipId}")
    public AmKnowledgeRelation detail(@PathVariable String relationshipId) {
        return relationRepository.findById(relationshipId).orElseThrow(() -> new RuntimeException("记录不存在"));
    }

    /**
     * 删除
     */
    @DeleteMapping("/{relationshipId}")
    public void delete(@PathVariable String relationshipId) {
        relationRepository.deleteById(relationshipId);
    }
} 